import os.path

import requests
from jinja2 import Environment, FileSystemLoader
import datetime
from DrissionPage import Chromium, ChromiumOptions


def os_screenshot(template, filename, data, element):
    # 设置 Jinja2 模板环境，指定 HTML 文件所在的目录
    env = Environment(loader=FileSystemLoader('.'))
    template = env.get_template(template)
    # # 定义要替换的变量
    template_data = {
        'data': data,
    }
    rendered_html = template.render(template_data)

    # 将渲染后的 HTML 保存到文件
    with open('depository/output.html', 'w', encoding='utf-8') as f:
        f.write(rendered_html)

    # 创建配置对象时指定要读取的ini文件路径
    co = ChromiumOptions()
    co.incognito()
    # co.headless()  # 无头模式
    co.set_argument('--start-maximized')
    co.set_argument('--force-device-scale-factor=0.75')

    # 使用该配置对象创建页面
    browser = Chromium(addr_or_opts=co)

    tab = browser.latest_tab
    tab.get(rf'{os.getcwd()}\depository\output.html')

    tab.ele(element).get_screenshot(path=filename)
    _console('截图已保存：', filename)
    browser.quit()


def get_week_range():
    today = datetime.datetime.today()
    start_of_week = today - datetime.timedelta(days=today.weekday())  # 获取周一日期
    end_of_week = start_of_week + datetime.timedelta(days=6)  # 获取周日日期

    return f"{start_of_week.strftime('%Y.%m.%d')}-{end_of_week.strftime('%Y.%m.%d')}"


def query(data):
    resp = requests.post(url, headers=headers, json=data)
    if resp.status_code != 200:
        raise ValueError('查询数据失败')
    result = resp.json()
    if result['code'] != 0:
        _console('error', result)
        raise ValueError(result['msg'])

    return result['data']['list']


url = 'http://pcserver.touni.top:9000/yunqing/query'
headers = {
    "accept": "application/json",
    "Content-Type": "application/json"
}


def main():
    folder = datetime.datetime.now().strftime('%Y-%m-%d')
    if not os.path.isdir(f'images/{folder}'):
        os.makedirs(f'images/{folder}')
    screenshot_folder = f'images/{folder}'
    # 1. 贵池关键存储设备配置备份执行截图
    data = {
        'api': '/wb/api/v1/task/getTaskExecRecordList',
        'data': {
            "page": 1,
            "rows": 50,
            "filter": {
                "taskId": "TSOpofmL",
                "poolIds": [
                    "BJtZflvl"
                ]
            }
        }
    }
    query_rows = query(data)
    filename = datetime.datetime.now().strftime('%Y.%m.%d')
    params = {
        'template': 'depository/模板_贵池关键存储设备配置备份执行截图.html',
        'filename': f'{screenshot_folder}/贵池关键存储设备配置备份执行截图{filename}.png',
        'data': query_rows,
        'element': 'xpath://*[@id="app"]/div/section/main/div[2]/div/div/div[2]/div/div[4]/div[2]/div[2]'
    }
    os_screenshot(**params)

    # 2. 贵池关键存储设备巡检执行截图
    data = {
        'api': '/wb/api/v1/insp/new/getInspectionExecRecord',
        'data': {
            "page": 1,
            "rows": 50,
            "filter": {
                "tenantId": 282,
                "inspType": 0,
                "inspName": "分布式",
                "poolIds": []
            }
        }
    }
    query_rows = query(data)
    filename = datetime.datetime.now().strftime('%Y.%m.%d')
    params = {
        'template': 'depository/模板_操作系统巡检.html',
        'filename': f'{screenshot_folder}/贵池关键存储设备巡检执行截图{filename}.png',
        'data': query_rows,
        'element': 'xpath://*[@id="app"]/div/section/main/div[2]/div/div[2]/div/div/div/div[2]/div[3]/div[1]/div[4]/div[2]/div[2]'
    }
    os_screenshot(**params)

    # 3. 贵池非关键存储设备巡检执行截图
    data = {
        'api': '/wb/api/v1/insp/new/getInspectionExecRecord',
        'data': {
            "page": 1,
            "rows": 50,
            "filter": {
                "tenantId": 282,
                "inspId": "12eyZNtcyk",
                "inspType": 0
            }
        }
    }
    query_rows = query(data)
    filename = get_week_range()
    params = {
        'template': 'depository/模板_操作系统巡检.html',
        'filename': f'{screenshot_folder}/贵池非关键存储设备巡检执行截图{filename}.png',
        'data': query_rows,
        'element': 'xpath://*[@id="app"]/div/section/main/div[2]/div/div[2]/div/div/div/div[2]/div[3]/div[1]/div[4]/div[2]/div[2]'
    }
    os_screenshot(**params)

    # 4. 贵池操作系统巡检执行截图
    data = {
        'api': '/wb/api/v1/insp/new/getInspectionExecRecord',
        'data': {
            "page": 1,
            "rows": 50,
            "filter": {
                "tenantId": 282,
                "inspType": 8,
                "inspName": "日常",
                "poolIds": []
            }
        }
    }
    query_rows = query(data)
    filename = get_week_range()
    params = {
        'template': 'depository/模板_操作系统巡检.html',
        'filename': f'{screenshot_folder}/贵池操作系统巡检执行截图{filename}.png',
        'data': query_rows,
        'element': 'xpath://*[@id="app"]/div/section/main/div[2]/div/div[2]/div/div/div/div[2]/div[3]/div[1]/div[4]/div[2]/div[2]'
    }
    os_screenshot(**params)

    # # 5. 贵池服务器硬件巡检执行截图
    data = {
        'api': '/wb/api/v1/inspHardwareTask/selHardwareInspTask',
        'data': {
            "page": 1,
            "rows": 50,
            "filter": {
                "taskId": "kMFhobpw"
            }
        }
    }
    query_rows = query(data)
    filename = get_week_range()
    params = {
        'template': 'depository/模板_硬件巡检.html',
        'filename': f'{screenshot_folder}/贵池服务器硬件巡检执行截图{filename}.png',
        'data': query_rows,
        'element': 'xpath://*[@id="app"]/div/section/main/div[2]/div/div[1]/div/div[2]/div[1]/div/div/div[4]/div[2]/div[2]'
    }
    os_screenshot(**params)

    # 6. 贵池关键存储设备重保巡检执行截图
    data = {
        'api': '/wb/api/v1/insp/new/getInspectionExecRecord',
        'data': {
            "page": 1,
            "rows": 50,
            "filter": {
                "tenantId": 282,
                "inspId": "8p3kNbKP",
                "inspType": 0
            }
        }
    }
    query_rows = query(data)
    filename = datetime.datetime.now().strftime('%Y.%m.%d')
    params = {
        'template': 'depository/模板_操作系统巡检.html',
        'filename': f'{screenshot_folder}/贵池关键存储设备重保巡检执行截图{filename}-0点-18点.png',
        'data': query_rows,
        'element': 'xpath://*[@id="app"]/div/section/main/div[2]/div/div[2]/div/div/div/div[2]/div[3]/div[1]/div[4]/div[2]/div[2]'
    }
    os_screenshot(**params)
